#include <list>
#include <nice2d/actions/parallelaction.h>

class ParallelActionData
{
public:
    bool setTarget = false;
    std::list<ActionPointer> actions;
};

ParallelAction::ParallelAction():
    data(new ParallelActionData)
{
}

ParallelAction::~ParallelAction()
{
}

void ParallelAction::addAction(ActionPointer action)
{
    data->actions.push_back(action);
}

void ParallelAction::clear()
{
    data->actions.clear();
    stop();
}

void ParallelAction::update(float deltaTime)
{
    if (getStatus() != ActionStatus_Running)
        return;

    if (!data->setTarget) {
        assert(!getOwner().expired());
        std::for_each(data->actions.begin(), data->actions.end(), [&](ActionPointer action) {
            action->setOwner(getOwner().lock());
        });
        data->setTarget = true;
    }

    auto itr = data->actions.begin();
    for (; itr != data->actions.end(); itr++) {
        auto action = *itr;
        action->update(deltaTime);
    }

    data->actions.remove_if([](ActionPointer action)->bool{return action->getStatus() == ActionStatus_Done;});
    if (data->actions.empty())
        stop();
}
